<?php

namespace app\api\service;

use app\model\Sign;
use app\model\User;
use think\Exception;


/**
 * 微信登录
 * 如果担心频繁被恶意调用，请限制ip
 * 以及访问频率
 */
class UserService
{
    /**
     * 参与活动
    */
    public static function joinPay($uid){
        $today_date = date('Y-m-d');
        $obj_sign = Sign::where([
            'uid'=>$uid,
            'join_date'=>$today_date,
        ])->find();
        if(!$obj_sign){
            Sign::create([
                'uid'=>$uid,
                'join_date'=>$today_date,
                'jointime'=>time(),
            ]);
        }
        User::where(['id'=>$uid])->setInc('join_times', 1);
        return true;
    }

    /**
     * 签到
    */
    public static function sign($uid){
        $yesterDay = date('Y-m-d',strtotime('-1 day'));
        $obj_sign = Sign::where([
            'uid'=>$uid,
            'join_date'=>$yesterDay,
        ])->find();
        if($obj_sign){
            throw new \Exception('未参与昨天活动');
        }
        $obj_sign->signtime = time();
        $obj_sign->is_sign = 1;
        $obj_sign->save();
        User::where(['id'=>$uid])->setInc('sign_times', 1);
        return true;
    }

    /**
     * 统计某个日期签到情况
    */
    public static function countSignInfo($date){
        $res = Sign::where(['join_date'=>$date])
            ->group('is_sign')
            ->field(['count(*)'])
            ->select();
        if(!array_key_exists(Sign::SIGNED_NO,$res)){
            $res[Sign::SIGNED_NO] = 0;
        }
        if(!array_key_exists(Sign::SIGNED_YES,$res)){
            $res[Sign::SIGNED_YES] = 0;
        }

        return $res;
    }

    /**
     * 统计某个日期的参与情况
    */
    public static function countJoinInfo($date){
        $res = Sign::where(['join_date'=>$date])
            ->group('is_sign')
            ->field(['count(*) as count'])
            ->find();
        return $res->count;
    }

}
